package com.lsj.spring.config;

import com.lsj.spring.mapper.UserMapper;
import lombok.Data;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Lsj
 * @version 1.0
 * @date 2021/6/24 19:49
 * configuration是一个配置类
 * enableAspectJAutoProxy开启对aspectj的支持
 */
@Configuration
@ComponentScan("com.lsj.spring")
@PropertySource("classpath:jdbc.properties")
@Data
@Import(JdbcConfig.class)
@EnableAspectJAutoProxy
public class SpringConfig {
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    @Value("测试者:皮卡丘")
    private String name;

    /**
     * 初始化
     */
    @PostConstruct
    public void init(){
        System.out.println("初始化");
    }

    /**
     * 创建session工厂
     * @return 映射器找到usermapper中的sql发送给数据库
     * @throws IOException 异常
     */
    @Bean
    public UserMapper userMapper() throws IOException {
        System.out.println(this.username);
        // 读取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 获得session工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 获取session
        SqlSession session = sqlSessionFactory.openSession();
        return session.getMapper(UserMapper.class);
    }
}
